package com.league.zjxn.main

import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import com.blankj.utilcode.util.ActivityUtils
import com.league.zjxn.R
import com.league.zjxn.app.SPSConstance
import com.league.zjxn.main.access.AccessActivity
import com.module.lemlin.owner.OwnerAbstractActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : OwnerAbstractActivity() {

    companion object {
        fun open() {
            ActivityUtils.startActivity(MainActivity::class.java)
        }
    }

    private val fragmentLifecycleCallbacks =
        object : FragmentManager.FragmentLifecycleCallbacks() {
            override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
                super.onFragmentResumed(fm, f)
            }
        }

    override val layoutResId: Int
        get() = R.layout.activity_main

    override fun initView() {

        if (SPSConstance.token.isNullOrEmpty() || SPSConstance.userInfo == null) {
            finish()
            AccessActivity.open()
        }

        val fragments: MutableList<Fragment> = mutableListOf(
            MainHomeFragment.newInstance(),
            MainProjectFragment.newInstance(),
            MainLeagueFragment.newInstance(),
            MainMessageFragment.newInstance(),
            MainMineFragment.newInstance()
        )

        nvpMainBody.offscreenPageLimit = fragments.size
        nvpMainBody.apply {
            setScrollAnim(false)
        }.adapter = object : FragmentStatePagerAdapter(
            supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {
            override fun getItem(position: Int): Fragment = fragments[position]

            override fun getCount(): Int = fragments.size

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {

            }
        }
        supportFragmentManager.registerFragmentLifecycleCallbacks(
            fragmentLifecycleCallbacks, (false)
        )

        rbMainBottomHome.setOnClickListener {
            nvpMainBody.currentItem = 0
        }

        rbMainBottomProject.setOnClickListener {
            nvpMainBody.currentItem = 1
        }

        ivMainBottomLeague.setOnClickListener {
            nvpMainBody.currentItem = 2
            rgMainBottomGroup.clearCheck()
        }

        rbMainBottomMessage.setOnClickListener {
            nvpMainBody.currentItem = 3
        }

        rbMainBottomMine.setOnClickListener {
            nvpMainBody.currentItem = 4
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        supportFragmentManager.unregisterFragmentLifecycleCallbacks(fragmentLifecycleCallbacks)
    }

}